package main

import (
	"fmt"
	"strings"

	"github.com/minph/conf"
	"github.com/minph/fs"
)

// App 配置数据
var App = conf.New("app.conf")

func main() {
	path := App.GetValue("main", "path")
	keyword := App.GetValue("main", "keyword")

	search(path, keyword)
}

func search(path, keyword string) {
	dir := fs.NewDir(path)

	if !dir.Exist() {
		fmt.Printf("路径 %v 不存在\n", path)
		fmt.Scanln()
		return
	}

	if len(keyword) == 0 {
		fmt.Printf("请配置关键词\n")
		fmt.Scanln()
		return
	}

	fmt.Printf("搜索路径：%v\n关键词：%v\n", path, keyword)

	var result []string
	lineMap := make(map[string][]int)
	list, _ := dir.All()

	for _, file := range list {
		flag := true
		content, _ := fs.ReadByRow(file)
		for index, line := range content {
			if strings.Contains(line, keyword) {

				if flag {
					result = append(result, file)
					flag = false
				}
				if _, ok := lineMap[file]; ok {
					lineMap[file] = append(lineMap[file], index+1)
				} else {
					lineMap[file] = []int{index}
				}
			}
		}
	}

	if len(result) == 0 {
		fmt.Println("未发现匹配文件")
	}

	for i, item := range result {
		fmt.Printf("%v => %v  行数%v\n", i, item, lineMap[item])
	}

	fmt.Scanln()
}
